package zmee.pmas.opplugin;

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.CloneUtils;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.dynamicobject.DynamicObjectType;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.db.tx.TX;
import kd.bos.db.tx.TXHandle;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.bos.entity.plugin.args.BeginOperationTransactionArgs;
import kd.bos.exception.KDBizException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.DispatchServiceHelper;
import kd.bos.servicehelper.operation.DeleteServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.pmgt.pmas.opplugin.team.OutBudgetOp;
import kd.pmgt.pmbs.common.enums.*;
import kd.pmgt.pmbs.common.utils.StageStatusHelper;
import kd.pmgt.pmbs.servicehelper.BudgetCtrlHelper;

import java.math.BigDecimal;
import java.time.ZoneId;
import java.util.*;

public class OutBudgetOpplugin extends AbstractOperationServicePlugIn {
    private static final String BUDGETCTRL = "budgetctrl";
    private static final String BUDGETPRONAME = "budgetproname";
    private static final String BUDGETPRONUMBER = "budgetpronumber";
    private static final String BUDGETPRO = "budgetpro";
    public static final String BUDGET_CONTROL_MODE = "budgetcontrolmode";
    public static final String PROJECT_COST_CONTROL = "projectcostcontrol";
    public static final String REALBUDGETENTRY = "realbudgetentry";
    public static final String OUTBUDGET_FORMID = "pmas_outbudget";
    private static final Log LOG = LogFactory.getLog(OutBudgetOp.class);

    public OutBudgetOpplugin() {
    }

    public void onPreparePropertys(PreparePropertysEventArgs e) {
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.add("billno");
        fieldKeys.add("sourcetype");
        fieldKeys.add("version");
        fieldKeys.add("project");
        fieldKeys.add("isvalid");
        fieldKeys.add("currency");
        fieldKeys.add("budgetstage");
        fieldKeys.add("type");
        fieldKeys.add("project");
        fieldKeys.add("totalamount");
        fieldKeys.add("year");
        fieldKeys.add("treeentryentity");
        fieldKeys.add("budgetamount");
        fieldKeys.add("budgetitem");
        fieldKeys.add("budgetitemname");
        fieldKeys.add("descriptionentry");
        fieldKeys.add("isGroupNode");
        fieldKeys.add("pid");
        fieldKeys.add("projectbudgetitem");
        fieldKeys.add("siamount");
        fieldKeys.add("viamount");
        fieldKeys.add("vichangeamount");
        fieldKeys.add("sichangeamount");
        fieldKeys.add("budgetctrl");
        fieldKeys.add("budgetcontrolmode");
        fieldKeys.add("projectcostcontrol");
        fieldKeys.add("budgetproname");
        fieldKeys.add("budgetpronumber");
        fieldKeys.add("budgetpro");
        fieldKeys.add("budgetperiod");
        fieldKeys.add("treeentryentity.seq");
        fieldKeys.add("realbudgetentry");
        fieldKeys.add("projectapplydate");
        fieldKeys.add("group");
        fieldKeys.add("realbudgetentry.seq");
        fieldKeys.add("realbudgetentry.realprobudgetname");
        fieldKeys.add("realbudgetentry.realbudgetitem");
        fieldKeys.add("realbudgetentry.realundertakeorg");
        fieldKeys.add("realbudgetentry.realundertakeperiod");
        fieldKeys.add("realbudgetentry.realproname");
        fieldKeys.add("realbudgetentry.realpronumber");
        fieldKeys.add("realbudgetentry.realproid");
        fieldKeys.add("realbudgetentry.realbeforeamt");
        fieldKeys.add("realbudgetentry.realundertakeamt");
        fieldKeys.add("realbudgetentry.realdifferenceamt");
        fieldKeys.add("treeentryentity.seq");
        fieldKeys.add("controlinfoentry.entryproid");
    }

    public void beginOperationTransaction(BeginOperationTransactionArgs e) {
        String operationKey = e.getOperationKey();
        DynamicObject[] dataEntities = e.getDataEntities();
        byte var5 = -1;
        switch(operationKey.hashCode()) {
            case -1335458389:
                if (operationKey.equals("delete")) {
                    var5 = 4;
                }
                break;
            case -891535336:
                if (operationKey.equals("submit")) {
                    var5 = 1;
                }
                break;
            case -5031951:
                if (operationKey.equals("unsubmit")) {
                    var5 = 2;
                }
                break;
            case 3522941:
                if (operationKey.equals("save")) {
                    var5 = 0;
                }
                break;
            case 93166555:
                if (operationKey.equals("audit")) {
                    var5 = 3;
                }
        }

        DynamicObject[] var6;
        int var7;
        int var8;
        DynamicObject dataEntity;
        switch(var5) {
            case 0:
                var6 = dataEntities;
                var7 = dataEntities.length;

                for(var8 = 0; var8 < var7; ++var8) {
                    dataEntity = var6[var8];
                    Long pk = (Long)dataEntity.getPkValue();
                    if (pk != 0L) {
                        QFilter qFilter = new QFilter("relatebillid", "=", pk.toString());
                        DynamicObject curBudgetRecord = BusinessDataServiceHelper.loadSingle("pmco_budgetrecord", "id, billno", new QFilter[]{qFilter});
                        if (curBudgetRecord != null) {
                            curBudgetRecord.set("billno", dataEntity.get("billno"));
                            SaveServiceHelper.save(new DynamicObject[]{curBudgetRecord});
                        }
                    }
                }

                return;
            case 1:
                this.doSubmit(dataEntities);
                break;
            case 2:
                this.doUnsubmit(dataEntities);
                break;
            case 3:
                var6 = dataEntities;
                var7 = dataEntities.length;

                for(var8 = 0; var8 < var7; ++var8) {
                    dataEntity = var6[var8];
                    String budgetControlMode = dataEntity.getString("budgetcontrolmode");
                    if (StringUtils.equals(budgetControlMode, BudgetCtlModeEnum.CONTROLANDADJUST.getValue())) {
                        this.returnOccupyChangeAmount(dataEntity, "audit");
                    }
                }

                this.doAudit(dataEntities);
                break;
            case 4:
                var6 = dataEntities;
                var7 = dataEntities.length;

                for(var8 = 0; var8 < var7; ++var8) {
                    dataEntity = var6[var8];
                    this.deleteBudgetRecord(dataEntity);
                }
        }

    }

    protected void doSubmit(DynamicObject[] dataEntities) {
        DynamicObject[] var2 = dataEntities;
        int var3 = dataEntities.length;

        for(int var4 = 0; var4 < var3; ++var4) {
            DynamicObject obj = var2[var4];
            BigDecimal version = obj.getBigDecimal("version");
            DynamicObject budgetStage = obj.getDynamicObject("budgetstage");
            DynamicObject project = obj.getDynamicObject("project");
            if (budgetStage != null && BigDecimal.valueOf(1.0D).compareTo(version) == 0 && StringUtils.equals(budgetStage.getString("number"), BudgetStageEnum.PREINSTALL_2.getValue())) {
                StageStatusHelper.changeStatus(project, ProjectStageEnum.FEASIBILITYSTUDYSTAGE_S, ProjectStatusEnum.APPROVAL_IN);
            }

            String budgetControlMode = obj.getString("budgetcontrolmode");
            if (StringUtils.equals(budgetControlMode, BudgetCtlModeEnum.CONTROLANDOCCUPY.getValue())) {
                QFilter proFilter = new QFilter("project", "=", project.getPkValue());
                QFilter validFilter = new QFilter("isvalid", "=", "1");
                DynamicObject[] lastBillObjs = BusinessDataServiceHelper.load("pmas_outbudget", "id,year", new QFilter[]{proFilter, validFilter}, "year desc", 1);
                if (lastBillObjs.length > 0) {
                    DynamicObject lastBillObj = lastBillObjs[0];
                    Date preBudgetDate = lastBillObj.getDate("year");
                    Date budgetDate = obj.getDate("year");
                    int curYear = budgetDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate().getYear();
                    int preYear = preBudgetDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate().getYear();
                    if (preYear != curYear) {
                        this.occupyChangeAmount(obj, "submit");
                    } else {
                        lastBillObj = this.getLastBillObj(obj, project, "submit");
                        this.occupyAmount(obj, lastBillObj, "submit");
                    }
                }
            } else if (StringUtils.equals(budgetControlMode, BudgetCtlModeEnum.CONTROLANDADJUST.getValue())) {
                this.occupyChangeAmount(obj, "submit");
            }
        }

    }

    protected void saveBudgetRecord(DynamicObject dataEntity) {
        String billNo = dataEntity.getString("billno");
        Long pk = (Long)dataEntity.getPkValue();
        QFilter qFilter;
        if (pk == 0L) {
            qFilter = new QFilter("billno", "=", billNo);
        } else {
            qFilter = new QFilter("relatebillid", "=", pk.toString());
        }

        DynamicObject budgetRecord = BusinessDataServiceHelper.loadSingle("pmco_budgetrecord", "billno, billstatus, creator, auditor, org, auditdate, createtime, modifytime, modifier, project, relatebillid, billsource, budgetstage, totalamount, group, currency, projectapplydate, budgetcontrolmode, projectcostcontrol, isvalid, description,year,realbudgetentry.id, realbudgetentry.seq, realbudgetentry.realprobudgetname, realbudgetentry.realbudgetitem, realbudgetentry.realundertakeorg, realbudgetentry.realundertakeperiod, realbudgetentry.realproname, realbudgetentry.realpronumber, realbudgetentry.realproid, realbudgetentry.realbeforeamt, realbudgetentry.realundertakeamt, realbudgetentry.realdifferenceamt", new QFilter[]{qFilter});
        if (budgetRecord != null) {
            String billSource = budgetRecord.getString("billsource");
            if (StringUtils.equals("pmas_outbudget", billSource)) {
                this.setBudgetRecordFieldValue(dataEntity, budgetRecord, true);
            } else {
                DynamicObjectType dt = EntityMetadataCache.getDataEntityType("pmco_budgetrecord");
                budgetRecord = new DynamicObject(dt);
                budgetRecord.set("id", ORM.create().genLongId("pmco_budgetrecord"));
                this.setBudgetRecordFieldValue(dataEntity, budgetRecord, false);
            }
        } else {
            DynamicObjectType dt = EntityMetadataCache.getDataEntityType("pmco_budgetrecord");
            budgetRecord = new DynamicObject(dt);
            budgetRecord.set("id", ORM.create().genLongId("pmco_budgetrecord"));
            this.setBudgetRecordFieldValue(dataEntity, budgetRecord, false);
        }

        SaveServiceHelper.save(new DynamicObject[]{budgetRecord});
    }

    protected void setBudgetRecordFieldValue(DynamicObject dataEntity, DynamicObject budgetRecord, boolean isExistRecord) {
        String budgetControlMode = dataEntity.getString("budgetcontrolmode");
        budgetRecord.set("billno", dataEntity.get("billno"));
        budgetRecord.set("billstatus", StatusEnum.UNCHECKED.getValue());
        budgetRecord.set("org", dataEntity.get("org"));
        budgetRecord.set("year", dataEntity.getDate("year"));
        budgetRecord.set("billsource", "pmas_outbudget");
        Long pk = (Long)dataEntity.getPkValue();
        if (pk != 0L) {
            budgetRecord.set("relatebillid", pk.toString());
        }

        budgetRecord.set("budgetstage", dataEntity.get("budgetstage"));
        budgetRecord.set("totalamount", dataEntity.get("totalamount"));
        budgetRecord.set("group", dataEntity.get("group"));
        budgetRecord.set("currency", dataEntity.get("currency"));
        budgetRecord.set("projectapplydate", dataEntity.get("projectapplydate"));
        budgetRecord.set("project", dataEntity.get("project"));
        budgetRecord.set("budgetcontrolmode", budgetControlMode);
        budgetRecord.set("projectcostcontrol", dataEntity.get("projectcostcontrol"));
        if (!isExistRecord) {
            budgetRecord.set("createtime", new Date());
        }

        budgetRecord.set("modifytime", new Date());
        DynamicObjectCollection realBudgetEntryCol = dataEntity.getDynamicObjectCollection("realbudgetentry");
        DynamicObjectCollection outBudgetControlInfoEntry = budgetRecord.getDynamicObjectCollection("realbudgetentry");
        DynamicObjectType type = outBudgetControlInfoEntry.getDynamicObjectType();
        outBudgetControlInfoEntry.clear();

        DynamicObject outBudgetControlInfo;
        for(Iterator var9 = realBudgetEntryCol.iterator(); var9.hasNext(); outBudgetControlInfoEntry.add(outBudgetControlInfo)) {
            DynamicObject realBudgetEntry = (DynamicObject)var9.next();
            outBudgetControlInfo = new DynamicObject(type);
            outBudgetControlInfo.set("seq", realBudgetEntry.get("seq"));
            outBudgetControlInfo.set("realprobudgetname", realBudgetEntry.get("realprobudgetname"));
            outBudgetControlInfo.set("realbudgetitem", realBudgetEntry.get("realbudgetitem"));
            outBudgetControlInfo.set("realundertakeorg", realBudgetEntry.get("realundertakeorg"));
            outBudgetControlInfo.set("realundertakeperiod", realBudgetEntry.get("realundertakeperiod"));
            outBudgetControlInfo.set("realproname", realBudgetEntry.get("realproname"));
            outBudgetControlInfo.set("realpronumber", realBudgetEntry.get("realpronumber"));
            outBudgetControlInfo.set("realproid", realBudgetEntry.get("realproid"));
            BigDecimal realdifferenceamt;
            if (StringUtils.equals(budgetControlMode, BudgetCtlModeEnum.CONTROLANDOCCUPY.getValue())) {
                outBudgetControlInfo.set("realbeforeamt", realBudgetEntry.get("realbeforeamt"));
                outBudgetControlInfo.set("realundertakeamt", realBudgetEntry.get("realundertakeamt"));
                realdifferenceamt = realBudgetEntry.getBigDecimal("realdifferenceamt");
                if (realdifferenceamt.compareTo(BigDecimal.ZERO) == 0) {
                    realdifferenceamt = realBudgetEntry.getBigDecimal("realundertakeamt").subtract(realBudgetEntry.getBigDecimal("realbeforeamt"));
                }

                outBudgetControlInfo.set("realdifferenceamt", realdifferenceamt);
            } else if (StringUtils.equals(budgetControlMode, BudgetCtlModeEnum.CONTROLANDADJUST.getValue())) {
                realdifferenceamt = realBudgetEntry.getBigDecimal("realdifferenceamt").compareTo(BigDecimal.ZERO) > 0 ? realBudgetEntry.getBigDecimal("realdifferenceamt") : BigDecimal.ZERO;
                if (realdifferenceamt.compareTo(BigDecimal.ZERO) == 0) {
                    realdifferenceamt = realBudgetEntry.getBigDecimal("realundertakeamt").subtract(realBudgetEntry.getBigDecimal("realbeforeamt"));
                }

                outBudgetControlInfo.set("realundertakeamt", realdifferenceamt);
            }
        }

    }

    protected DynamicObject getLastBillObj(DynamicObject obj, DynamicObject project, String operationKey) {
        QFilter proFilter = new QFilter("project", "=", project.getPkValue());
        QFilter statusFilter = new QFilter("billstatus", "=", StatusEnum.UNCHECKED.getValue());
        QFilter sourceTypeFilter = new QFilter("sourcetype", "=", BudgetSourceTypeEnum.OUT.getValue());
        DynamicObject[] proBudgets;
        if (StringUtils.equals("submit", operationKey)) {
            proBudgets = BusinessDataServiceHelper.load("pmas_outbudget", "id, billno", new QFilter[]{proFilter, statusFilter, sourceTypeFilter});
            if (proBudgets.length > 0) {
                DynamicObject proBudget = proBudgets[0];
                throw new KDBizException(String.format(ResManager.loadKDString("存在已提交状态支出预算单据“%s”，请先将该单审核通过，才能提交。", "OutBudgetOp_4", "pmgt-pmas-opplugin", new Object[0]), proBudget.getString("billno")));
            }
        }

        statusFilter = new QFilter("billstatus", "=", "C");
        proBudgets = BusinessDataServiceHelper.load("pmas_outbudget", "id", new QFilter[]{proFilter, statusFilter, sourceTypeFilter});
        if (proBudgets.length <= 1) {
            proFilter = new QFilter("pro", "=", project.getPkValue());
            return BusinessDataServiceHelper.loadSingle("pmas_pro_approval", "id,projectapplydate", new QFilter[]{proFilter});
        } else {
            QFilter validFilter = new QFilter("isvalid", "=", "1");
            DynamicObject[] lastBillObj = BusinessDataServiceHelper.load("pmas_outbudget", "id,year", new QFilter[]{proFilter, validFilter, sourceTypeFilter}, "year desc", 1);
            return lastBillObj.length > 0 ? lastBillObj[0] : null;
        }
    }

    protected void occupyAmount(DynamicObject curObj, DynamicObject lastObj, String curOperate) {
        DynamicObject lastBudgetRecord = null;
        String billNo = curObj.getString("billno");

        DynamicObject newBudgetRecord;
        String msg2;
        String msg3;
        try {
            QFilter qFilter = new QFilter("relatebillid", "=", lastObj.getPkValue().toString());
            lastBudgetRecord = BusinessDataServiceHelper.loadSingle("pmco_budgetrecord", "id, billno", new QFilter[]{qFilter});
            if (lastBudgetRecord != null) {
                msg2 = lastBudgetRecord.getString("billno");
                msg3 = String.format(ResManager.loadKDString("支出预算单“%1$s”%2$s操作，对上一张单“%3$s”调用企业绩效云“预算返还接口“BgControlService.returnBudget”，返还操作%4$s：", "OutBudgetOp_5", "pmgt-pmas-opplugin", new Object[0]), billNo, curOperate, msg2, "unsubmitoccupy");
                BudgetCtrlHelper.returnBudget(lastBudgetRecord, "pmco_budgetrecord", "unsubmitoccupy", msg3);
            }

            msg2 = String.format(ResManager.loadKDString("支出预算单“%1$s”%2$s操作，调用企业绩效云“预算扣减接口“BgControlService.requestBudget”做占用，占用操作%3$s：", "OutBudgetOp_6", "pmgt-pmas-opplugin", new Object[0]), billNo, curOperate, "submitoccupy");
            qFilter = new QFilter("relatebillid", "=", curObj.getPkValue().toString());
            newBudgetRecord = BusinessDataServiceHelper.loadSingle("pmco_budgetrecord", "id, billno, relatebillid", new QFilter[]{qFilter});
            if (newBudgetRecord == null) {
                qFilter = new QFilter("billno", "=", billNo);
                QFilter billSourceFilter = new QFilter("billsource", "=", "pmas_outbudget");
                newBudgetRecord = BusinessDataServiceHelper.loadSingle("pmco_budgetrecord", "id, billno, relatebillid", new QFilter[]{qFilter, billSourceFilter});
            }

            if (newBudgetRecord != null) {
                newBudgetRecord.set("relatebillid", curObj.getPkValue().toString());
                BudgetCtrlHelper.requestBudget(newBudgetRecord, "pmco_budgetrecord", "submitoccupy", true, msg2);
            }
        } catch (Exception var10) {
            if (lastBudgetRecord != null) {
                msg2 = lastBudgetRecord.getString("billno");
                msg3 = String.format(ResManager.loadKDString("支出预算单“%1$s”%2$s操作，调用企业绩效云“预算扣减接口“BgControlService.requestBudget”做占用，占用操作%3$s：发生异常，对上一张单“%s”重新占用。", "OutBudgetOp_7", "pmgt-pmas-opplugin", new Object[0]), billNo, curOperate, "submitoccupy", msg2);
                BudgetCtrlHelper.requestBudget(lastBudgetRecord, "pmco_budgetrecord", "submitoccupy", true, msg3);
            }

            LOG.error(var10);
            throw new KDBizException(var10.toString());
        }

        if (newBudgetRecord != null) {
            SaveServiceHelper.save(new DynamicObject[]{newBudgetRecord});
        }

    }

    protected void returnOccupyAmount(DynamicObject curObj, DynamicObject lastObj, String curOperate) {
        String billNo = curObj.getString("billno");
        DynamicObject lastBudgetRecord = null;

        try {
            String msg1 = String.format(ResManager.loadKDString("支出预算单“%1$s”%2$s操作，调用企业绩效云“预算返还接口“BgControlService.returnBudget”，返还操作%3$s：", "OutBudgetOp_8", "pmgt-pmas-opplugin", new Object[0]), billNo, curOperate, "unsubmitoccupy");
            QFilter qFilter = new QFilter("relatebillid", "=", curObj.getPkValue().toString());
            DynamicObject newBudgetRecord = BusinessDataServiceHelper.loadSingle("pmco_budgetrecord", "id, billno", new QFilter[]{qFilter});
            BudgetCtrlHelper.returnBudget(newBudgetRecord, "pmco_budgetrecord", "unsubmitoccupy", msg1);
            qFilter = new QFilter("relatebillid", "=", lastObj.getPkValue().toString());
            lastBudgetRecord = BusinessDataServiceHelper.loadSingle("pmco_budgetrecord", "id, billno", new QFilter[]{qFilter});
            if (lastBudgetRecord != null) {
                String lastBillNo = lastBudgetRecord.getString("billno");
                String msg2 = String.format(ResManager.loadKDString("支出预算单“%1$s”%2$s操作，对上一张单“%3$s”调用企业绩效云“预算扣减接口“BgControlService.requestBudget”做占用，占用操作%4$s：", "OutBudgetOp_9", "pmgt-pmas-opplugin", new Object[0]), billNo, curOperate, lastBillNo, "submitoccupy");
                BudgetCtrlHelper.requestBudget(lastBudgetRecord, "pmco_budgetrecord", "submitoccupy", true, msg2);
            }

        } catch (Exception var11) {
            if (lastBudgetRecord != null) {
                String lastBillNo = lastBudgetRecord.getString("billno");
                String msg3 = String.format(ResManager.loadKDString("支出预算单“%1$s”%2$s操作，对上一张单调用企业绩效云“预算扣减接口“BgControlService.requestBudget”做占用，占用操作%3$s：发生异常。", "OutBudgetOp_10", "pmgt-pmas-opplugin", new Object[0]), billNo, curOperate, lastBillNo, "submitoccupy");
                LOG.error(msg3);
            }

            LOG.error(var11);
            throw new KDBizException(var11.toString());
        }
    }

    protected void occupyChangeAmount(DynamicObject curObj, String curOperate) {
        String billNo = curObj.getString("billno");
        DynamicObject newBudgetRecord = null;

        try {
            String msg1 = String.format(ResManager.loadKDString("支出预算单“%1$s”%2$s操作，调用企业绩效云“预算扣减接口“BgControlService.requestBudget”做占用，占用操作%3$s：", "OutBudgetOp_6", "pmgt-pmas-opplugin", new Object[0]), billNo, curOperate, "submitoccupy");
            QFilter qFilter = new QFilter("relatebillid", "=", curObj.getPkValue().toString());
            newBudgetRecord = BusinessDataServiceHelper.loadSingle("pmco_budgetrecord", "id, billno, relatebillid", new QFilter[]{qFilter});
            if (newBudgetRecord == null) {
                qFilter = new QFilter("billno", "=", billNo);
                QFilter billSourceFilter = new QFilter("billsource", "=", "pmas_outbudget");
                newBudgetRecord = BusinessDataServiceHelper.loadSingle("pmco_budgetrecord", "id, billno, relatebillid", new QFilter[]{qFilter, billSourceFilter});
            }

            if (newBudgetRecord != null) {
                newBudgetRecord.set("relatebillid", curObj.getPkValue().toString());
                BudgetCtrlHelper.requestBudget(newBudgetRecord, "pmco_budgetrecord", "submitoccupy", true, msg1);
            }
        } catch (Exception var8) {
            LOG.error(var8);
            throw new KDBizException(var8.toString());
        }

        if (newBudgetRecord != null) {
            SaveServiceHelper.save(new DynamicObject[]{newBudgetRecord});
        }

    }

    protected void returnOccupyChangeAmount(DynamicObject curObj, String curOperate) {
        String billNo = curObj.getString("billno");

        try {
            String msg1 = String.format(ResManager.loadKDString("支出预算单“%1$s”%2$s操作，调用企业绩效云“预算返还接口“BgControlService.returnBudget”，返还操作%3$s：", "OutBudgetOp_8", "pmgt-pmas-opplugin", new Object[0]), billNo, curOperate, "unsubmitoccupy");
            QFilter qFilter = new QFilter("relatebillid", "=", curObj.getPkValue().toString());
            DynamicObject newBudgetRecord = BusinessDataServiceHelper.loadSingle("pmco_budgetrecord", "id, billno", new QFilter[]{qFilter});
            if (newBudgetRecord != null) {
                BudgetCtrlHelper.returnBudget(newBudgetRecord, "pmco_budgetrecord", "unsubmitoccupy", msg1);
            }

        } catch (Exception var7) {
            LOG.error(var7);
            throw new KDBizException(var7.toString());
        }
    }

    protected void doAudit(DynamicObject[] dataEntities) {
        List<DynamicObject> updateObjs = new ArrayList();
        List<DynamicObject> auditObjs = new ArrayList(10);
        List<DynamicObject> updateProjectItems = new ArrayList();
        List<DynamicObject> addProjectItems = new ArrayList();
        DynamicObject[] var6 = dataEntities;
        int var7 = dataEntities.length;

        for(int var8 = 0; var8 < var7; ++var8) {
            DynamicObject obj = var6[var8];
            DynamicObject project = obj.getDynamicObject("project");
            QFilter proFilter = new QFilter("project", "=", project.getPkValue());
            QFilter isValid = new QFilter("isvalid", "=", "1");
            QFilter yearValid = new QFilter("year", "=", obj.getDate("year"));
            QFilter sourceTypeFilter = new QFilter("sourcetype", "=", BudgetSourceTypeEnum.OUT.getValue());
            DynamicObject[] validObjs = BusinessDataServiceHelper.load("pmas_budget", "id,billno,isvalid", new QFilter[]{proFilter, isValid, sourceTypeFilter, yearValid});
            if (validObjs.length > 0) {
                DynamicObject[] var16 = validObjs;
                int var17 = validObjs.length;

                for(int var18 = 0; var18 < var17; ++var18) {
                    DynamicObject budget = var16[var18];
                    budget.set("isvalid", DefaultEnum.NO.getValue());
                    updateObjs.add(budget);
                }
            }

            obj.set("isvalid", DefaultEnum.YES.getValue());
            String budgetControlMode = obj.getString("budgetcontrolmode");
            if (StringUtils.equals(budgetControlMode, BudgetCtlModeEnum.CONTROLANDADJUST.getValue())) {
                DynamicObjectCollection treeEntryEntity = obj.getDynamicObjectCollection("treeentryentity");
                if (!treeEntryEntity.isEmpty()) {
                    this.generateAdjustForm(obj, BudgetCtrlEnum.AUDIT);
                }
            }

            auditObjs.add(obj);
            ProjectBudgetGenerateHelper.generateProjectBudget(obj, updateProjectItems, addProjectItems, BudgetSourceTypeEnum.OUT.getValue());
            DynamicObject lastBillObj = this.getLastBillObj(obj, project, "audit");
            this.updateBudgetRecordField(obj, lastBillObj, "audit");
        }

        if (!updateObjs.isEmpty()) {
            SaveServiceHelper.update((DynamicObject[])updateObjs.toArray(new DynamicObject[updateObjs.size()]));
        }

        if (!auditObjs.isEmpty()) {
            SaveServiceHelper.update((DynamicObject[])auditObjs.toArray(new DynamicObject[auditObjs.size()]));
        }

        if (!updateProjectItems.isEmpty()) {
            SaveServiceHelper.save(((DynamicObject)updateProjectItems.get(0)).getDataEntityType(), updateProjectItems.toArray(new DynamicObject[updateProjectItems.size()]));
        }

        if (!addProjectItems.isEmpty()) {
            SaveServiceHelper.save(((DynamicObject)addProjectItems.get(0)).getDataEntityType(), addProjectItems.toArray(new DynamicObject[addProjectItems.size()]));
        }

    }

    protected void updateBudgetRecordField(DynamicObject dataEntity, DynamicObject lastBillObj, String operate) {
        QFilter qFilter = new QFilter("relatebillid", "=", dataEntity.getPkValue().toString());
        DynamicObject curBudgetRecord = BusinessDataServiceHelper.loadSingle("pmco_budgetrecord", "billno, billstatus, creator, auditor, org, auditdate, createtime, modifytime, modifier, project, relatebillid, billsource, budgetstage, totalamount, group, currency, projectapplydate, budgetcontrolmode, projectcostcontrol, isvalid, description,year", new QFilter[]{qFilter});
        String budgetControlMode = dataEntity.getString("budgetcontrolmode");
        if (curBudgetRecord != null) {
            if (!StringUtils.equals(budgetControlMode, BudgetCtlModeEnum.NOTCONTROL.getValue())) {
                if (StringUtils.equals(budgetControlMode, BudgetCtlModeEnum.CONTROLANDOCCUPY.getValue())) {
                    if (StringUtils.equals(operate, "audit")) {
                        curBudgetRecord.set("billstatus", StatusEnum.CHECKED.getValue());
                        curBudgetRecord.set("isvalid", Boolean.TRUE);
                        curBudgetRecord.set("modifytime", new Date());
                        curBudgetRecord.set("auditdate", new Date());
                        qFilter = new QFilter("relatebillid", "=", lastBillObj.getPkValue().toString());
                        DynamicObject lastBudgetRecord = BusinessDataServiceHelper.loadSingle("pmco_budgetrecord", "billno, billstatus, creator, auditor, org, auditdate, createtime, modifytime, modifier, project, relatebillid, billsource, budgetstage, totalamount, group, currency, projectapplydate, budgetcontrolmode, projectcostcontrol, isvalid, description,year", new QFilter[]{qFilter});
                        int curRecordDate = curBudgetRecord.getDate("year").toInstant().atZone(ZoneId.systemDefault()).toLocalDate().getYear();
                        int lastBillDate = lastBudgetRecord.getDate("year").toInstant().atZone(ZoneId.systemDefault()).toLocalDate().getYear();
                        if (curRecordDate == lastBillDate) {
                            lastBudgetRecord.set("isvalid", Boolean.FALSE);
                        }

                        SaveServiceHelper.save(new DynamicObject[]{curBudgetRecord, lastBudgetRecord});
                    } else if (StringUtils.equals(operate, "unsubmit")) {
                        curBudgetRecord.set("billstatus", StatusEnum.TEMPSAVE.getValue());
                        curBudgetRecord.set("isvalid", Boolean.FALSE);
                        curBudgetRecord.set("modifytime", new Date());
                        SaveServiceHelper.save(new DynamicObject[]{curBudgetRecord});
                    }
                } else if (StringUtils.equals(operate, "audit")) {
                    curBudgetRecord.set("billstatus", StatusEnum.CHECKED.getValue());
                    curBudgetRecord.set("isvalid", Boolean.TRUE);
                    curBudgetRecord.set("modifytime", new Date());
                    curBudgetRecord.set("auditdate", new Date());
                    SaveServiceHelper.save(new DynamicObject[]{curBudgetRecord});
                } else if (StringUtils.equals(operate, "unsubmit")) {
                    curBudgetRecord.set("billstatus", StatusEnum.TEMPSAVE.getValue());
                    curBudgetRecord.set("isvalid", Boolean.FALSE);
                    curBudgetRecord.set("modifytime", new Date());
                    SaveServiceHelper.save(new DynamicObject[]{curBudgetRecord});
                }

            }
        }
    }

    protected void deleteBudgetRecord(DynamicObject dataEntity) {
        String budgetControlMode = dataEntity.getString("budgetcontrolmode");
        if (StringUtils.equals(budgetControlMode, BudgetCtlModeEnum.CONTROLANDOCCUPY.getValue()) || StringUtils.equals(budgetControlMode, BudgetCtlModeEnum.CONTROLANDADJUST.getValue())) {
            QFilter qFilter = new QFilter("relatebillid", "=", dataEntity.getPkValue().toString());
            DynamicObject curBudgetRecord = BusinessDataServiceHelper.loadSingle("pmco_budgetrecord", "id, billno", new QFilter[]{qFilter});
            if (curBudgetRecord != null) {
                DeleteServiceHelper.delete(EntityMetadataCache.getDataEntityType("pmco_budgetrecord"), new Object[]{curBudgetRecord.getPkValue()});
            }

        }
    }

    protected void doUnsubmit(DynamicObject[] dataEntities) {
        DynamicObject[] var2 = dataEntities;
        int var3 = dataEntities.length;

        for(int var4 = 0; var4 < var3; ++var4) {
            DynamicObject obj = var2[var4];
            String budgetControlMode = obj.getString("budgetcontrolmode");
            int curYear;
            int preYear;
            if (StringUtils.equals(budgetControlMode, BudgetCtlModeEnum.CONTROLANDOCCUPY.getValue())) {
                DynamicObject project = obj.getDynamicObject("project");
                QFilter proFilter = new QFilter("project", "=", project.getPkValue());
                QFilter validFilter = new QFilter("isvalid", "=", "1");
                DynamicObject[] lastBillObjs = BusinessDataServiceHelper.load("pmas_outbudget", "id,year", new QFilter[]{proFilter, validFilter}, "year desc", 1);
                if (lastBillObjs.length > 0) {
                    DynamicObject lastBillObj = lastBillObjs[0];
                    Date preBudgetDate = lastBillObj.getDate("year");
                    Date budgetDate = obj.getDate("year");
                    curYear = budgetDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate().getYear();
                    preYear = preBudgetDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate().getYear();
                    if (preYear != curYear) {
                        this.returnOccupyChangeAmount(obj, "unsubmit");
                        this.updateBudgetRecordField(obj, (DynamicObject)null, "unsubmit");
                    } else {
                        lastBillObj = this.getLastBillObj(obj, project, "unsubmit");
                        this.returnOccupyAmount(obj, lastBillObj, "unsubmit");
                        this.updateBudgetRecordField(obj, lastBillObj, "unsubmit");
                    }
                }
            } else if (StringUtils.equals(budgetControlMode, BudgetCtlModeEnum.CONTROLANDADJUST.getValue())) {
                this.returnOccupyChangeAmount(obj, "unsubmit");
                this.updateBudgetRecordField(obj, (DynamicObject)null, "unsubmit");
            }

            BigDecimal version = obj.getBigDecimal("version");
            DynamicObject budgetstage = obj.getDynamicObject("budgetstage");
            DynamicObject project = obj.getDynamicObject("project");
            if (budgetstage != null && BigDecimal.valueOf(1.0D).compareTo(version) == 0 && StringUtils.equals(budgetstage.getString("number"), BudgetStageEnum.PREINSTALL_2.getValue())) {
                boolean exist = false;
                QFilter filter1 = new QFilter("project", "=", project.getPkValue());
                DynamicObject[] proTask = BusinessDataServiceHelper.load("pmpm_task", "assigner,projectstatus,number,name,status,creator,modifier,enable,createtime,modifytime,masterid,longnumber,level,fullname,isleaf, parent, controllevel, majortype, tasktype, achievementnode, pretask, logical, relativeduration, absoluteduration, planstarttime, planendtime, aimfinishtime, comptimedeviation, responsibleperson, responsibledept, cooperationperson, cooperationdept, comment, realendtime, resultdoc, prechangetask, version, realtimedeviation, belongplantype, sourcetask, completionstatus, percent, sharer, project, relationtask, islatest, taskseq, planid, riskcolor, responsiblepost, associatepost, templatetask, tasksource, expecttime, multicooperationperson, multicooperationdept, completedescription,taskresultdocentry,billstatus,meettask", new QFilter[]{filter1});
                if (proTask != null && proTask.length > 0) {
                    DynamicObject[] var27 = proTask;
                    curYear = proTask.length;

                    for(preYear = 0; preYear < curYear; ++preYear) {
                        DynamicObject task = var27[preYear];
                        DynamicObject majortype = task.getDynamicObject("majortype");
                        if (StringUtils.equals(majortype.getString("number"), MajorTypeEnum.FEASIBILITYSTUDY_S.getValue())) {
                            QFilter filter3 = new QFilter("billstatus", "=", StatusEnum.CHECKED.getValue());
                            filter3.or(new QFilter("billstatus", "=", StatusEnum.UNCHECKED.getValue()));
                            QFilter filter4 = new QFilter("task", "=", task.getPkValue());
                            DynamicObject[] taskReport = BusinessDataServiceHelper.load("pmpm_taskreport", "id,billno,billstatus,persontype,creator,modifier,auditor,auditdate,modifytime,createtime,chengguoentity.id,chengguoentity.attachmentfield,chengguoentity.resultname,chengguoentity.desc,chengguoentity.force,chengguoentity.resultid,chengguoentity.frequency,iscomplete,completetime,tips,reportdesc,huibaojlentity.id,huibaojlentity.completeprocess,huibaojlentity.resultdate,huibaojlentity.reportperson,huibaojlentity.completedesc,huibaojlentity.taskreport,huibaojlentity.historytask,huibaojlentity.resultstatus,task,percent,huibaoperson", new QFilter[]{filter3, filter4});
                            if (taskReport != null && taskReport.length > 0) {
                                exist = true;
                                break;
                            }
                        }
                    }
                }

                if (!exist) {
                    StageStatusHelper.changeStatus(project, ProjectStageEnum.FEASIBILITYSTUDYSTAGE_S, (ProjectStatusEnum)null);
                }
            }
        }

    }

    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        String operationKey = e.getOperationKey();
        DynamicObject[] dataEntities = e.getDataEntities();
        byte var5 = -1;
        switch(operationKey.hashCode()) {
            case -891535336:
                if (operationKey.equals("submit")) {
                    var5 = 0;
                }
                break;
            case 93166555:
                if (operationKey.equals("audit")) {
                    var5 = 1;
                }
        }

        DynamicObject[] var6;
        int var7;
        int var8;
        DynamicObject dataEntity;
        BigDecimal totalamount;
        String budgetControlMode;
        DynamicObjectCollection treeEntryEntity;
        switch(var5) {
            case 0:
                var6 = dataEntities;
                var7 = dataEntities.length;

                for(var8 = 0; var8 < var7; ++var8) {
                    dataEntity = var6[var8];
                    totalamount = dataEntity.getBigDecimal("totalamount");
                    budgetControlMode = dataEntity.getString("budgetcontrolmode");
                    if (StringUtils.equals(budgetControlMode, BudgetCtlModeEnum.CONTROLANDADJUST.getValue())) {
                        if (totalamount.compareTo(BigDecimal.ZERO) > 0) {
                            treeEntryEntity = dataEntity.getDynamicObjectCollection("treeentryentity");
                            if (treeEntryEntity.isEmpty()) {
                                e.setCancelMessage(ResManager.loadKDString("提交失败。该项目企业预算控制方式为“受控，立项时调剂”，填写支出预算金额需要具体到预算明细，请输入支出预算明细。", "OutBudgetOp_11", "pmgt-pmas-opplugin", new Object[0]));
                                e.setCancel(true);
                            } else {
                                this.validateBudgetBalance(dataEntity, DefaultEnum.YES.getValue());
                                this.saveBudgetRecord(dataEntity);
                            }
                        }
                    } else if (StringUtils.equals(budgetControlMode, BudgetCtlModeEnum.CONTROLANDOCCUPY.getValue()) && totalamount.compareTo(BigDecimal.ZERO) > 0) {
                        treeEntryEntity = dataEntity.getDynamicObjectCollection("realbudgetentry");
                        if (treeEntryEntity.isEmpty()) {
                            throw new KDBizException(ResManager.loadKDString("提交失败。该项目企业预算控制方式为“受控，立项时占用”，填写支出预算金额需要具体到预算明细，请输入支出预算明细。", "OutBudgetOp_12", "pmgt-pmas-opplugin", new Object[0]));
                        }

                        this.saveBudgetRecord(dataEntity);
                    }
                }

                return;
            case 1:
                var6 = dataEntities;
                var7 = dataEntities.length;

                for(var8 = 0; var8 < var7; ++var8) {
                    dataEntity = var6[var8];
                    totalamount = dataEntity.getBigDecimal("totalamount");
                    budgetControlMode = dataEntity.getString("budgetcontrolmode");
                    if (StringUtils.equals(budgetControlMode, BudgetCtlModeEnum.CONTROLANDADJUST.getValue()) && totalamount.compareTo(BigDecimal.ZERO) > 0) {
                        treeEntryEntity = dataEntity.getDynamicObjectCollection("treeentryentity");
                        if (treeEntryEntity.isEmpty()) {
                            e.setCancelMessage(ResManager.loadKDString("提交失败。该项目企业预算控制方式为“受控，立项时调剂”，填写支出预算金额需要具体到预算明细，请输入支出预算明细。", "OutBudgetOp_11", "pmgt-pmas-opplugin", new Object[0]));
                            e.setCancel(true);
                        }
                    }
                }
        }

    }

    /** @deprecated */
    @Deprecated
    protected void filterOutBudgetEntry(DynamicObject dataEntity) {
        DynamicObjectCollection outBudgetEntries = dataEntity.getDynamicObjectCollection("treeentryentity");
        DynamicObjectCollection removeEntries = new DynamicObjectCollection();
        Iterator var4 = outBudgetEntries.iterator();

        while(var4.hasNext()) {
            DynamicObject item = (DynamicObject)var4.next();
            if (item.getLong("pid") != 0L) {
                removeEntries.add(item);
            }
        }

        if (!removeEntries.isEmpty()) {
            outBudgetEntries.removeAll(removeEntries);
        }

    }

    protected void filterOutBudgetEntry(DynamicObjectCollection outBudgetEntryCol) {
        DynamicObjectCollection removeEntries = new DynamicObjectCollection();
        Iterator var3 = outBudgetEntryCol.iterator();

        while(var3.hasNext()) {
            DynamicObject item = (DynamicObject)var3.next();
            if (item.getLong("pid") != 0L) {
                removeEntries.add(item);
            }
        }

        if (!removeEntries.isEmpty()) {
            outBudgetEntryCol.removeAll(removeEntries);
        }

    }

    protected void generateAdjustForm(DynamicObject dataEntity, BudgetCtrlEnum type) {
        CloneUtils cloneUtils = new CloneUtils(false, false);
        DynamicObject obj = (DynamicObject)cloneUtils.clone(dataEntity);
        this.filterOutBudgetEntry(obj);
        String changeAmountProp = this.getAdjustMoneyProp(obj);
        this.mergeBudgetItem(obj, changeAmountProp);
        this.invokeAdjustInterface(obj, type);
    }

    protected void invokeAdjustInterface(DynamicObject dataEntity, BudgetCtrlEnum type) {
        Map<String, Object> dimmember = new HashMap();
        DynamicObject project = dataEntity.getDynamicObject("project");
        String newDimmemNumber = project.getString("number");
        String newDimmemName = project.getString("name");
        dimmember.put("new_dimmemNumber", newDimmemNumber);
        dimmember.put("new_dimmemName", newDimmemName);
        dimmember.put("userId", RequestContext.get().getUserId());
        dimmember.put("entrytityName", "realbudgetentry");
        dimmember.put("budgetMoney", "realdifferenceamt");
        dimmember.put("budgetitem", "realbudgetitem");
        dimmember.put("ebMemberNumKey", "realpronumber");
        dimmember.put("proMemberIdKey", "realproid");
        dimmember.put("costOrgKey", "realundertakeorg");
        dimmember.put("costPeriodKey", "realundertakeperiod");
        dimmember.put("restoreData", type.getValue());
        String result = null;
        LOG.info(String.format(ResManager.loadKDString("调用企业绩效云预算调剂单接口“IAdjustExternalInvokeService.adjustAudio”，传递的参数[dimmember]数据为：%1$s，[dataentity]数据为：%2$s。", "OutBudgetOp_14", "pmgt-pmas-opplugin", new Object[0]), dimmember, dataEntity));
        TXHandle h = TX.requiresNew();
        Throwable var9 = null;

        try {
            try {
                result = (String) DispatchServiceHelper.invokeBizService("epm", "eb", "IAdjustExternalInvokeService", "adjustAudio", new Object[]{dataEntity, dimmember});
            } catch (Exception var19) {
                h.markRollback();
                throw new KDBizException(var19.getMessage());
            }
        } catch (Throwable var20) {
            var9 = var20;
            throw var20;
        } finally {
            if (h != null) {
                if (var9 != null) {
                    try {
                        h.close();
                    } catch (Throwable var18) {
                        var9.addSuppressed(var18);
                    }
                } else {
                    h.close();
                }
            }

        }

        LOG.info(String.format(ResManager.loadKDString("调用企业绩效云预算调剂单接口“IAdjustExternalInvokeService.adjustAudio”，接口返回的数据为：%s", "OutBudgetOp_2", "pmgt-pmas-opplugin", new Object[0]), result));
        if (result == null) {
            throw new KDBizException(String.format(ResManager.loadKDString("调用企业绩效云接口未返回任何数据，接口类型：%s", "OutBudgetOp_13", "pmgt-pmas-opplugin", new Object[0]), type.getName()));
        }
    }

    /** @deprecated */
    @Deprecated
    protected void mergeBudgetItem(DynamicObject dataEntity, String changeAmountProp) {
        DynamicObjectCollection outBudgetEntries = dataEntity.getDynamicObjectCollection("treeentryentity");
        Map<Object, DynamicObject> budgetItemMap = new HashMap(outBudgetEntries.size());

        Iterator var5;
        DynamicObject item;
        DynamicObject budgetItem;
        for(var5 = outBudgetEntries.iterator(); var5.hasNext(); budgetItemMap.put(budgetItem, item)) {
            item = (DynamicObject)var5.next();
            budgetItem = item.getDynamicObject("budgetitem");
            DynamicObject object = (DynamicObject)budgetItemMap.get(budgetItem);
            if (object != null) {
                BigDecimal amount = object.getBigDecimal(changeAmountProp).add(item.getBigDecimal(changeAmountProp));
                item.set(changeAmountProp, amount);
            }
        }

        if (!budgetItemMap.isEmpty()) {
            outBudgetEntries.clear();
            var5 = budgetItemMap.entrySet().iterator();

            while(var5.hasNext()) {
                Map.Entry<Object, DynamicObject> entry = (Map.Entry)var5.next();
                budgetItem = (DynamicObject)entry.getValue();
                BigDecimal changeAmount = budgetItem.getBigDecimal(changeAmountProp);
                if (changeAmount != null && changeAmount.intValue() != 0) {
                    outBudgetEntries.add(budgetItem);
                }
            }
        }

    }

    /** @deprecated */
    @Deprecated
    protected String getAdjustMoneyProp(DynamicObject dataEntity) {
        DynamicObject project = dataEntity.getDynamicObject("project");
        String changeAmountProp = null;
        String type = dataEntity.getString("type");
        if (StringUtils.equals(type, "ADJUST")) {
            changeAmountProp = "vichangeamount";
        } else {
            boolean isExistedProBudgets = this.isExistBudgetCurProject(project);
            if (!isExistedProBudgets) {
                changeAmountProp = "budgetamount";
            } else {
                changeAmountProp = "sichangeamount";
            }
        }

        return changeAmountProp;
    }

    protected void validateBudgetBalance(DynamicObject dataEntity, String queryBalance) {
        this.generateAdjustForm(dataEntity, BudgetCtrlEnum.SUBMIT);
    }

    protected boolean isExistBudgetCurProject(DynamicObject project) {
        QFilter proFilter = new QFilter("project", "=", project.getPkValue());
        QFilter typeFilter = new QFilter("sourcetype", "=", BudgetSourceTypeEnum.OUT.getValue());
        QFilter validFilter = new QFilter("isvalid", "=", "1");
        DynamicObject[] existedProBudgets = BusinessDataServiceHelper.load("pmas_budget", "id", new QFilter[]{proFilter, typeFilter, validFilter}, "budgetstage.seqno", 1);
        return existedProBudgets != null && existedProBudgets.length > 0;
    }
}
